<template>
  <div class="view">
    <el-radio-group v-model="status" @change="handleStatusChange" class="select">
      <el-radio-button label='' class="no-select">所有订单</el-radio-button>
      <el-radio-button label="1" class="no-select">待付款订单</el-radio-button>
      <el-radio-button label="2" class="no-select">已付款订单</el-radio-button>
      <el-radio-button label="3" class="no-select">已取消订单</el-radio-button>
    </el-radio-group>
    <!-- 查询 -->
    <el-form :inline="true" :model="selectForm" class="demo-form-inline">
      <el-form-item label="订单号:">
        <el-input v-model="selectForm.number" placeholder="请填写订单号" clearable></el-input>
      </el-form-item>

      <el-form-item label="下单时间:">
        <el-date-picker v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-button type="primary" style="margin-left: 10px;" @click="pageQuery()">查询</el-button>
    </el-form>
    <!-- 数据展示 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="订单号" width="120">
      </el-table-column>
      <el-table-column prop="airlineName" label="航空名称" width="220">
      </el-table-column>
      <el-table-column prop="userName" label="姓名" width="120">
      </el-table-column>
      <el-table-column prop="userPhone" label="手机号" width="150">
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="150">
      </el-table-column>
      <el-table-column prop="price" label="实付款" width="100">
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 1">待付款</span>
          <span v-else-if="scope.row.status === 3">已取消</span>
          <span v-else-if="scope.row.status === 2">已付款</span>
          <span v-else>未知状态</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="操作">
        <template slot-scope="scope">
          <!-- <el-button type="text" @click="detail(scope.row)">查看</el-button> -->
          <el-button type="text" @click="updataStatus(scope.row)">
            <span v-if="scope.row.status === 1">付款</span>
          </el-button>
          <!-- <el-button type="text" @click="updataStatus(scope.row)">
            <span v-if="scope.row.status === 2">已付款</span>
          </el-button> -->
          <el-button type="text" @click="cancel(scope.row)">
            <span v-if="scope.row.status !== 3 " style="color: #f56c6c;">取消订单</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页查询 -->
    <div class="block" style="margin-top: 20px; text-align:center;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
        :page-sizes="[6, 10, 14, 18]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- :before-close="" -->
    <el-dialog title="订单详情" :visible.sync="orderVisible">
      <div class="order-detail">
        <p><span class="label">订单号：</span>{{ odForm.number }}</p>
        
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      tableData: [],
      page: 1,
      pageSize: 6,
      total: '',
      status:'',
      dateTime: '',
      orderVisible: false,
      selectForm: {
        number: '',
      },
      odForm: {
        number: '',
      }
    }
  },
  created() {
    this.status = this.$route.query.status || '';
    console.log(this.status);
    this.getOrders(this.status);
  },
  methods: {
    handleStatusChange(status) {
      this.pageQuery(true);
    },
    deleteO(row) {
      this.$confirm('是否删除订单?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          url: '/api/order',
          method: 'delete',
          params: {
            id:row.id
          },
          headers: {
            token:this.$store.state.user.token
          }
        }).then(res => {
          if (res.data.code === 1) {
            console.log("删除成功");
            this.pageQuery();
          }
          else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        console.log("操作已取消");
        
      })
    },
    cancel(row) {
      this.$confirm('是否取消订单?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let status = 3;
        axios({
        url: `/api/order/status/${status}`,
        method: 'post',
        params: {
          id: row.id
        },
        headers: {
          token: this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          console.log("修改成功");
          this.pageQuery(true);
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(err => {
        this.handleError(err)
      })
      }).catch(() => {
        console.log("取消操作");
        
      })
    },
    updataStatus(row) {
      let status = '';
      if (row.status === 1) {
        status = 2;
      }
      else if (row.status !== 3) {
        status = 3;
      }
      axios({
        url: `/api/order/status/${status}`,
        method: 'post',
        params: {
          id: row.id
        },
        headers: {
          token: this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          console.log("修改成功");
          this.pageQuery(true);
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(err => {
        this.handleError(err)
      })
    },
    detail(row) {
      this.odForm = {
        number: row.number,
        phone: row.phone,
        consignee: row.consignee,
        address: row.address,
        amount: row.amount,
        goodsList: row.goodsList
      };
      this.orderVisible = true; 
    },
    getOrders(status) {
      this.status = status;
      this.pageQuery()
    },
    pageQuery(flag = false) {
      if (flag) {
        this.page = 1;
      }
      let beginTime = '';
      let endTime = '';
      if (this.dateTime && this.dateTime.length === 2) {
        // const date = this.dateTime.map(date => date.toISOString());
        const date = this.dateTime.map(date => {
          return date.toISOString().split('.')[0]; // 去掉毫秒和 'Z'
        });
        beginTime = date[0];
        endTime = date[1];
      }
      // alert(`${date[0]} , ${date[1]}`)
      axios({
        url: '/api/order/page',
        method: 'get',
        params: {
          beginTime: beginTime,
          endTime: endTime,
          status:this.status,
          number: this.selectForm.number,
          page: this.page,
          pageSize: this.pageSize,
        },
        headers: {
          token:this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          console.log("请求成功");
          this.total = res.data.data.total,
          this.tableData = res.data.data.records
        }
        else
        {
          this.$message.error(res.data.msg)
        }
      }).catch(err => {
        this.handleError(err);
      })
    },
    handleError(err) {
      console.error('An error occurred:', err);
      if (err.response) {
        if (err.response.status === 401) {
          this.$message.error("您的登录已过期，请重新登录");
          this.$router.push('/login')
        } else if (err.response.status === 500) {
          this.$message.error("服务器异常，请稍后再试");
          this.$router.push('/404')
        } else {
          this.$message.error("请求失败");
        }
      } else if (err.request) {
        this.$message.error("网络错误，请检查您的网络连接");
      } else {
        this.$message.error("请求异常！请稍后再试~");
      }
    },
    // 页码发生变化时发送请求
    handleCurrentChange(page) {
      this.page = page
      this.pageQuery()
    },
    // 每页数量发生变化发送请求
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageQuery(true)
    }
  }
}
</script>

<style scoped>
.order-detail {
  padding: 20px;
  font-size: 14px;
  line-height: 1.8;
}

.order-detail p {
  margin: 10px 0;
}

.order-detail .label {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  display: inline-block;
  width: 100px;
  /* 可根据需要调整宽度 */
}
.count {
  position: absolute;
  top: -5px;
  left: 105px;
  height: 14px;
  line-height: 14px;
  color: #fff;
  background-color: #e60012;
  padding: 0 5px;
  border-radius: 7px 7px 7px 0;
}
.dialog-footer {
  text-align: right;
}
.select{
  margin-left: 20px;
  height: 61px;
  width: auto;
  /* border: 1px solid green; */
  margin-bottom: 30px;
  padding-top: 10px;
}
.select .el-radio-button{
  height: 50px;
}
.demo-form-inline{
  margin-left: 40px;
}
.view {
  width: 96%;
  margin: 1% auto;
  border-radius: 10px;
  background-color: #ffffff;
  padding: 10px;
  overflow: hidden;
}
</style>